﻿using Common;
using MySql.Data.MySqlClient;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFake;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NB.MGJ.Service.FWSearch
{
    public class FWSearchService
    {
        public BaseRepository _baseRepository = new BaseRepository();

        public static void UpdateAntifakeLog_Provice_City(CodeLog model)
        {

          
            if (model.QueryIp == "::1" || model.QueryIp == "127.0.0.1")
            {
                model.QueryCity = "";
                model.QueryProvince = "";
                return;
            }

            //HttpClient httpclient = new System.Net.Http.HttpClient();
            //  httpclient.GetStringAsync("");

            String bodys = "";
            String url = "http://ip.taobao.com/service/getIpInfo.php";
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < model.QueryIp.Length)
            {
                url = url + "?ip=" + model.QueryIp;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((w, x, y, z) =>
                {
                    return true;
                });
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = "GET";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.UTF8);
            string a = Regex.Unescape(reader.ReadToEnd());
            var _string_a = a.Replace("\"", "").Split(new string[] { "region", "city" }, StringSplitOptions.RemoveEmptyEntries);
            int i = 2;
            
            foreach (Match item in Regex.Matches(a, "(\"region\"|\"city\"):\"([\\w]+)"))
            {
                if (i % 2 == 0)
                {
                    model.QueryProvince = item.Groups[item.Groups.Count - 1].Value;
                }
                else
                {
                    model.QueryCity = item.Groups[item.Groups.Count - 1].Value;
                }
                i += 1;
            }
        }

        public string Get_Provice_Ciry(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip) || ip == "127.0.0.1" || ip == "::1")
            {
                return "无法获取地址";
            }

            String bodys = "";
            String url = "http://ip.taobao.com/service/getIpInfo.php";
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < ip.Length)
            {
                url = url + "?ip=" + ip;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((w, x, y, z) =>
                {
                    return true;
                });
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = "GET";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.UTF8);
            string a = Regex.Unescape(reader.ReadToEnd());
            string result = string.Empty;
            foreach (Match item in Regex.Matches(a, "(\"region\"|\"city\"):\"([\\w]+)"))
            {
                result += item.Groups[item.Groups.Count - 1];
            }
            return result;
        }

        public void AddAntiFakeLog(CodeLog model, string Search)
        {
            string searchcode = string.Empty;
            if (!string.IsNullOrEmpty(Search))
            {
                searchcode = MiMa.Jiemi(Search, AppConst.DigitCodeKey);
            }
            searchcode = searchcode.Substring(0, 4);
            Task.Run(() =>
            {
                UpdateAntifakeLog_Provice_City(model);
                using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mgj_mysql"].ConnectionString))
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        string strCmd = string.Format("INSERT INTO nblogmain.codelog" + searchcode + "(`Fw_Code`,`QueryType`,`QueryIp`,`QueryTime`,`Valid`,`ProductId`,`EnterpriseId`,`Sex`,`Age`)VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", model.Fw_Code, model.QueryType, model.QueryIp, model.QueryTime, model.Valid, model.ProductId, model.EnterpriseId, model.Sex, model.Age);
                        cmd.CommandText = strCmd;
                        cmd.ExecuteNonQuery();
                    }
                }
            });
        }

        public PagedList<AntiFake_Digitcode> GetFwPageList(ref PagerModel pager, string Search)
        {
            string searchcode = string.Empty;
            string scode = string.Empty;
            if (!string.IsNullOrEmpty(Search))
            {
                searchcode = MiMa.Jiemi(Search, AppConst.DigitCodeKey);
            }
            searchcode = searchcode.Substring(0, 6);
            scode = searchcode.Substring(0, 4);
            pager.FldName = @"*";
            pager.TblName = @"( SELECT a.ID,a.Fw_CodeSecret,e.EnterpriseName,c.QueryType,c.QueryTime,a.EnterpriseId,c.QueryProvince,c.QueryCity,c.Valid,a.Flag,a.ProductId  FROM nbcodemain.antifake_digitcode" + searchcode + " a LEFT JOIN nblogmain.codelog" + scode + " c ON a.Fw_CodeSecret=c.Fw_Code LEFT JOIN organization_enterprise e on a.EnterpriseId=e.ID WHERE Fw_CodeSecret=" + Search + ") s";

            if (string.IsNullOrEmpty(pager.FldSort) || pager.FldSort == " ")
                pager.FldSort = " QueryTime desc ";
            MySqlParameter[] parameters = _baseRepository.SqParameterRefactor(ref pager);
            IEnumerable<AntiFake_Digitcode> resultList = _baseRepository.ExecuteStoredProcedureCollection<AntiFake_Digitcode>("Common_PageList", parameters);
            return new PagedList<AntiFake_Digitcode>(resultList, pager.Page, pager.PageSize, 1, Convert.ToInt32(parameters[6].Value));
        }
    }
}